package com.csx.data.orm.jpa.batch.util;

import javax.persistence.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 该类是 根据实体上的注解获取实体信息 的工具类
 */
public class TableEntityReflectUtil {

    private static final Logger logger = LoggerFactory.getLogger(TableEntityReflectUtil.class);

    /**
     * 类 -> 字段名称 -> 字段属性 的映射缓存
     */
    private static final Map<Class<?>, Map<String, Field>> CLAZZ_TO_COLUMN_FIELD_CACHE = new ConcurrentHashMap<>();


    /**
     * 根据实体类获取对应表名
     * @param clazz 实体类
     * @return 实体类对应的表名
     */
    public static String getTableName(Class<?> clazz) {

        Table table = clazz.getDeclaredAnnotation(Table.class);
        if(table != null) {
            return table.name();
        }
        return clazz.getSimpleName();
    }

    /**
     * 根据实体类获取其所有字段名 - 循环实现
     * @param clazz 实体类
     * @return 实体类对应的字段名列表
     */
    public static List<String> getColumns(Class<?> clazz) {

        List<String> columns = new ArrayList<>();
        while(!Object.class.equals(clazz)) {

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                Column column = field.getDeclaredAnnotation(Column.class);
                if(column != null) {
                    columns.add(column.name());
                    continue;
                }
                columns.add(field.getName());
            }
            clazz = clazz.getSuperclass();
        }
        return columns;
    }

    /**
     * 根据实体类 获取 ID 字段对应的名称 - 递归实现
     * @param clazz 实体类
     * @return 实体类ID对应的名称
     */
    public static String getId(Class<?> clazz) {
        if(Object.class.equals(clazz)) {
            return null;
        }
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Id id = field.getDeclaredAnnotation(Id.class);
            Column column = field.getDeclaredAnnotation(Column.class);
            if(id == null) {
                continue;
            }
            if(column != null) {
                return column.name();
            }
            return field.getName();
        }
        return getId(clazz.getSuperclass());
    }

    /**
     * 根据字段名和实体对象获取 实体对象中的字段值
     * @param column 字段名
     * @param entity 实体对象
     * @return 实体对象中字段名对应的字段值
     */
    public static Object getColumnValue(String column, Object entity) {

        Object res = null;
        try {
            Map<String, Field> columnToFieldMap = getColumnToFieldMap(entity.getClass());
            Field field = columnToFieldMap.get(column);
            res = field.get(entity);
        } catch (Exception e) {
            logger.error("getColumnValue failed because: ", e);
        }
        return res;
    }

    /**
     * 获取字段名到对应属性的映射Map
     * @param clazz 类
     * @return 字段名到对应属性的映射Map
     */
    public static Map<String, Field> getColumnToFieldMap(Class<?> clazz) {

        // Attempting to retrieve data from cache
        Map<String, Field> columnToFieldMap = CLAZZ_TO_COLUMN_FIELD_CACHE.get(clazz);
        if(columnToFieldMap != null) {
            return columnToFieldMap;
        }

        columnToFieldMap = new HashMap<>();
        while(!Object.class.equals(clazz)) {

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                // open access permissions
                field.setAccessible(true);
                Column column = field.getDeclaredAnnotation(Column.class);
                if(column != null) {
                    columnToFieldMap.put(column.name(), field);
                }else {
                    columnToFieldMap.put(field.getName(), field);
                }
            }
            clazz = clazz.getSuperclass();
        }

        // cache
        CLAZZ_TO_COLUMN_FIELD_CACHE.put(clazz, columnToFieldMap);
        return columnToFieldMap;
    }
}
